package com.lsyw.intergrate.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.lsyw.intergrate.common.util.DateUtil;
import com.lsyw.intergrate.common.util.EasyExcelUtil;
import com.lsyw.intergrate.entity.*;
import com.lsyw.intergrate.entity.vo.DeviceMonitorVo;
import com.lsyw.intergrate.service.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.lsyw.intergrate.entity.common.PageInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lsyw.intergrate.common.Result;
import org.springframework.util.CollectionUtils;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import io.swagger.annotations.Api;
import lombok.Data;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 监测数据日志表 前端控制器
 * </p>
 *
 * @author 刘磊
 * @since 2023-12-20
 */
@Api(tags = "监测数据日志表")
@RestController
@RequestMapping("/jc-massif-factor-value-log")
public class JcMassifFactorValueLogController {


    @Autowired
    private JcMassifFactorValueLogService jcMassifFactorValueLogService;
    @Autowired
    private JcMassifFactorValueService jcMassifFactorValueService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private MassifService massifService;
    @Autowired
    private JcFactorService jcFactorService;

    @PostMapping("/test")
    public Result test() {
        final LambdaQueryWrapper<JcMassifFactorValueLog> lambda = new QueryWrapper<JcMassifFactorValueLog>().lambda();
        lambda.eq(JcMassifFactorValueLog::getDelFlag, 0);
        lambda.isNull(JcMassifFactorValueLog::getDeviceNo);
        List<JcMassifFactorValueLog> dataVirtualList = jcMassifFactorValueLogService.list(lambda);
        dataVirtualList.forEach(e -> {
            final LambdaQueryWrapper<JcMassifFactorValue> lambda1 = new QueryWrapper<JcMassifFactorValue>().lambda();
            lambda1.eq(JcMassifFactorValue::getDelFlag, 0);
            lambda1.eq(JcMassifFactorValue::getJcMassifFactorValueLog, e.getId());
            List<JcMassifFactorValue> list = jcMassifFactorValueService.list(lambda1);
            e.setDeviceNo(list.get(0).getDeviceNo());
            jcMassifFactorValueLogService.updateById(e);

        });

        return Result.successResult(null);
    }

    @PostMapping("/test2")
    public Result test2() {
        final LambdaQueryWrapper<JcMassifFactorValue> lambda1 = new QueryWrapper<JcMassifFactorValue>().lambda();
        lambda1.eq(JcMassifFactorValue::getDelFlag, 0);
        lambda1.isNull(JcMassifFactorValue::getMaxValue);
        lambda1.like(JcMassifFactorValue::getFactorValue, "max");
        lambda1.orderByAsc(JcMassifFactorValue::getGmtCreate);
        List<JcMassifFactorValue> list = jcMassifFactorValueService.list(lambda1);
        list.forEach(e -> {
            JSONObject valueJson = JSON.parseObject(e.getFactorValue());
            if (valueJson.get("max") != null) {
                e.setMaxValue(Double.valueOf(valueJson.get("max").toString()));
                jcMassifFactorValueService.updateById(e);
            }

        });

        return Result.successResult(null);
    }


    /**
     * 分页查询
     */
    @ApiOperation(value = "设备最新监测数据")
    @GetMapping("/getDataBydeviceId")
    public Result deviceList(String deviceId) {
        if (deviceId == null || deviceId.equals("")) {
            return Result.errorResult("项目id为空");
        }
        Device device = deviceService.getById(deviceId);
        String cn = "2011";
        JcMassifFactorValueLog jcMassifFactorValueLog = jcMassifFactorValueLogService.getOneByDeviceNoAndCn(device.getCode(), cn);
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (jcMassifFactorValueLog != null) {
            final LambdaQueryWrapper<JcMassifFactorValue> lambda2 = new QueryWrapper<JcMassifFactorValue>().lambda();
            lambda2.eq(JcMassifFactorValue::getDelFlag, 0);
            lambda2.eq(JcMassifFactorValue::getJcMassifFactorValueLog, jcMassifFactorValueLog.getId());
            lambda2.isNotNull(JcMassifFactorValue::getValue);
            List<JcMassifFactorValue> list2 = jcMassifFactorValueService.list(lambda2);

            list2.forEach(k -> {
                Map<String, Object> map = new HashMap<>();
                JcFactor jcFactor = jcFactorService.getById(k.getJcFactorId());
                map.put("name", jcFactor.getName());
                map.put("unit", jcFactor.getUnitMeasurement());
                map.put("value", k.getValue());
                mapList.add(map);
            });
        }

        return Result.successResult(mapList);
    }

    /**
     * 分页查询
     */
    @ApiOperation(value = "设备数据监测")
    @PostMapping("/deviceList")
    public Result deviceList(@RequestBody Map<String, Object> condition) {
        if (condition.get("massifId") == null || condition.get("massifId").toString().equals("")) {
            return Result.errorResult("项目id为空");
        }
        final LambdaQueryWrapper<Device> lambda = new QueryWrapper<Device>().lambda();
        //TODO 自己的查询逻辑
        lambda.eq(Device::getMassifId, condition.get("massifId").toString());
        lambda.eq(Device::getType, "13");
        List<Device> list = deviceService.list(lambda);
        Massif massif = massifService.getById(condition.get("massifId").toString());
        List<DeviceMonitorVo> deviceMonitorVoList = new ArrayList<>();
        list.forEach(e -> {
            DeviceMonitorVo deviceMonitorVo = new DeviceMonitorVo();
            deviceMonitorVo.setId(e.getId());
            deviceMonitorVo.setName(e.getName());
            deviceMonitorVo.setMassifName(massif.getName());
            deviceMonitorVo.setType(e.getType());
            deviceMonitorVo.setMassifId(condition.get("massifId").toString());
            String cn = "";
            if (condition.get("type").toString().equals("1")) {
                cn = "2011";
            } else if (condition.get("type").toString().equals("2")) {
                cn = "2061";
            }
            JcMassifFactorValueLog jcMassifFactorValueLog = jcMassifFactorValueLogService.getOneByDeviceNoAndCn(e.getCode(), cn);
            if (jcMassifFactorValueLog != null) {
                deviceMonitorVo.setMonitorDate(DateUtil.formatTime(jcMassifFactorValueLog.getGmtCreate()));
                final LambdaQueryWrapper<JcMassifFactorValue> lambda2 = new QueryWrapper<JcMassifFactorValue>().lambda();
                lambda2.eq(JcMassifFactorValue::getDelFlag, 0);
                lambda2.eq(JcMassifFactorValue::getJcMassifFactorValueLog, jcMassifFactorValueLog.getId());
                lambda2.isNotNull(JcMassifFactorValue::getValue);
                List<JcMassifFactorValue> list2 = jcMassifFactorValueService.list(lambda2);
                List<Map<String, Object>> mapList = new ArrayList<>();
                list2.forEach(k -> {
                    Map<String, Object> map = new HashMap<>();
                    JcFactor jcFactor = jcFactorService.getById(k.getJcFactorId());
                    map.put("name", jcFactor.getName());
                    map.put("unit", jcFactor.getUnitMeasurement());
                    map.put("value", k.getValue());
                    mapList.add(map);
                });
                deviceMonitorVo.setMonitorData(mapList);
            }
            if (jcMassifFactorValueLog.getDeviceStatus() != null && jcMassifFactorValueLog.getDeviceStatus() != 1) {
                deviceMonitorVo.setDeviceStatus(2);
            } else {
                deviceMonitorVo.setDeviceStatus(1);
            }
            deviceMonitorVoList.add(deviceMonitorVo);
        });

        return Result.successResult(deviceMonitorVoList);
    }

    /**
     * 分页查询
     */
    @ApiOperation(value = "设备历史数据监测及趋势")
    @PostMapping("/page")
    public Result page(@RequestBody PageInfo pageInfo) {
        if (pageInfo.getCondition().get("deviceId") == null || Objects.equals(pageInfo.getCondition().get("deviceId").toString(), "")) {
            return Result.successResult(null);
        }
        JSONObject dataJson = new JSONObject();
        JSONObject rightJson = new JSONObject();
        Device device = deviceService.getById(pageInfo.getCondition().get("deviceId").toString());
        Page<JcMassifFactorValueLog> page = new Page<>();
        page.setSize(pageInfo.getPageSize());
        page.setCurrent(pageInfo.getPageNum());
        final LambdaQueryWrapper<JcMassifFactorValueLog> lambda = new QueryWrapper<JcMassifFactorValueLog>().lambda();
        if (pageInfo.getCondition().get("deviceId") != null && !Objects.equals(pageInfo.getCondition().get("deviceId").toString(), "")) {
            lambda.eq(JcMassifFactorValueLog::getDeviceNo, device.getCode());
        }
        if (pageInfo.getCondition().get("startDate") != null && !Objects.equals(pageInfo.getCondition().get("startDate").toString(), "")) {
            lambda.between(JcMassifFactorValueLog::getGmtCreate, DateUtil.getStartTime(DateUtil.parseDate(pageInfo.getCondition().get("startDate").toString())), DateUtil.getEndTime(DateUtil.parseDate(pageInfo.getCondition().get("endDate").toString())));
        }
        List<String> cnList = new ArrayList<>();
        String format = "";
        int idDay = 0;
        if (pageInfo.getCondition().get("type").toString().equals("1")) {
            cnList.add("2011");
            cnList.add("2021");
            format = "HH:mm";
        } else if (pageInfo.getCondition().get("type").toString().equals("2")) {
            cnList.add("2061");
            format = "HH";
        } else if (pageInfo.getCondition().get("type").toString().equals("3")) {
            cnList.add("2031");
            cnList.add("2041");
            format = "MM/dd";
            idDay = 1;
        }

        List<Map<String, Object>> headerList = new ArrayList<>();
        Map<String, Object> dateMap = new HashMap<>();
        dateMap.put("name", "采集时间");
        dateMap.put("key", "monitorDate");
        headerList.add(dateMap);
        List<JcFactor> jcFactorList = jcFactorService.getListByDeviceId(pageInfo.getCondition().get("deviceId").toString());
        jcFactorList.forEach(e -> {
            Map<String, Object> typeMap = new HashMap<>();
            typeMap.put("name", e.getName() + "(" + e.getUnitMeasurement() + ")");
            typeMap.put("key", e.getId());
            headerList.add(typeMap);
        });

        List<Map<String, Object>> bodyList = new ArrayList<>();
        List<String> dateTrendList = new ArrayList<>();
        String finalFormat = format;
        JSONObject jsonObject = new JSONObject();
        if (idDay == 0) {
            lambda.in(JcMassifFactorValueLog::getCn, cnList);
            lambda.eq(JcMassifFactorValueLog::getDelFlag, 0);
            lambda.orderByDesc(JcMassifFactorValueLog::getGmtCreate);
            IPage<JcMassifFactorValueLog> iPage = this.jcMassifFactorValueLogService.page(page, lambda);
            iPage.getRecords().forEach(e -> {
                Map<String, Object> map = new HashMap<>();
                map.put("monitorDate", DateUtil.formatTime(e.getGmtCreate()));
                final LambdaQueryWrapper<JcMassifFactorValue> lambda2 = new QueryWrapper<JcMassifFactorValue>().lambda();
                lambda2.eq(JcMassifFactorValue::getDelFlag, 0);
                lambda2.eq(JcMassifFactorValue::getJcMassifFactorValueLog, e.getId());
                lambda2.isNotNull(JcMassifFactorValue::getValue);
                List<JcMassifFactorValue> list2 = jcMassifFactorValueService.list(lambda2);
                jcFactorList.forEach(k -> {
                    Optional<JcMassifFactorValue> mapOptional = list2.stream().filter(b -> (
                                    b.getJcFactorId().equals(k.getId())
                            )
                    ).findFirst();
                    if (mapOptional.isPresent()) {
                        JcMassifFactorValue jcMassifFactorValue = mapOptional.get();
                        map.put(k.getId(), jcMassifFactorValue.getValue());
                    } else {
                        map.put(k.getId(), 0);
                    }
                });
                dateTrendList.add(DateUtil.format(e.getGmtCreate(), finalFormat));
                bodyList.add(map);

            });
            rightJson.put("dateList", recursiveReverse(dateTrendList));
            List<JSONObject> factorStackedLineChartList = new ArrayList<>();
            jcFactorList.forEach(e -> {
                JSONObject jcFactorJson = new JSONObject();
                jcFactorJson.put("factorName", e.getName());
                jcFactorJson.put("unit", e.getUnitMeasurement());
                List<String> valueList = new ArrayList<>();
                bodyList.forEach(k -> {
                    if (k.get(e.getId()) != null) {
                        valueList.add(k.get(e.getId()) + "");
                    } else {
                        valueList.add("0");
                    }
                });

                jcFactorJson.put("data", recursiveReverse(valueList));
                factorStackedLineChartList.add(jcFactorJson);


            });
            rightJson.put("factorStackedLineChartList", factorStackedLineChartList);
            jsonObject.put("page", iPage);
        }else{
            Map<String, Object> condition = new HashMap<>();
            condition.put("startTime",DateUtil.getStartTime(DateUtil.parseDate(pageInfo.getCondition().get("startDate").toString())));
            condition.put("endTime",DateUtil.getEndTime(DateUtil.parseDate(pageInfo.getCondition().get("endDate").toString())));
            condition.put("deviceNo",device.getCode());
            List<Map<String, Object>> mapList=jcMassifFactorValueService.getDayInfo(condition);
            Date startDate = DateUtil.parseDate(pageInfo.getCondition().get("startDate").toString());
            Date endDate = DateUtil.parseDate(pageInfo.getCondition().get("endDate").toString());
            int count=0;
            while (startDate.compareTo(endDate)<1){
                Map<String, Object> map = new HashMap<>();
                map.put("monitorDate", DateUtil.format(startDate));
                Date finalStartDate = startDate;
                jcFactorList.forEach(k -> {
                    Optional<Map<String, Object>> mapOptional = mapList.stream().filter(b -> (
                                    b.get("date").equals(DateUtil.format(finalStartDate))&&b.get("jcFactorId").equals(k.getId())
                            )
                    ).findFirst();
                    if (mapOptional.isPresent()) {
                        Map<String, Object> map1 = mapOptional.get();
                        map.put(k.getId(), map1.get("value"));
                    } else {
                        map.put(k.getId(), 0);
                    }
                });
                dateTrendList.add(DateUtil.format(startDate, finalFormat));
                bodyList.add(map);
                count++;
                startDate=DateUtil.addDays(startDate,1);
            }
            rightJson.put("dateList", recursiveReverse(dateTrendList));
            List<JSONObject> factorStackedLineChartList = new ArrayList<>();
            jcFactorList.forEach(e -> {
                JSONObject jcFactorJson = new JSONObject();
                jcFactorJson.put("factorName", e.getName());
                jcFactorJson.put("unit", e.getUnitMeasurement());
                List<String> valueList = new ArrayList<>();
                bodyList.forEach(k -> {
                    if (k.get(e.getId()) != null) {
                        valueList.add(k.get(e.getId()) + "");
                    } else {
                        valueList.add("0");
                    }
                });

                jcFactorJson.put("data", recursiveReverse(valueList));
                factorStackedLineChartList.add(jcFactorJson);


            });
            int finalCount = count;
            IPage<Map<String, Object>> iPage =new IPage<Map<String, Object>>() {
                @Override
                public List<OrderItem> orders() {
                    return null;
                }

                @Override
                public List<Map<String, Object>> getRecords() {
                    return null;
                }

                @Override
                public IPage<Map<String, Object>> setRecords(List<Map<String, Object>> records) {
                    return null;
                }

                @Override
                public long getTotal() {
                    return finalCount;
                }

                @Override
                public IPage<Map<String, Object>> setTotal(long total) {
                    return null;
                }

                @Override
                public long getSize() {
                    return finalCount;
                }

                @Override
                public IPage<Map<String, Object>> setSize(long size) {
                    return null;
                }

                @Override
                public long getCurrent() {
                    return 1;
                }

                @Override
                public IPage<Map<String, Object>> setCurrent(long current) {
                    return null;
                }
            };
            rightJson.put("factorStackedLineChartList", factorStackedLineChartList);
            jsonObject.put("page", iPage);
        }


        jsonObject.put("header", headerList);
        jsonObject.put("body", bodyList);
        dataJson.put("left", jsonObject);
        dataJson.put("right", rightJson);
        return Result.successResult(dataJson);
    }
    /**
     * 环境历史监测导出
     */
    @PostMapping("/hjInfoExcel")
    @ApiOperation(value = "环境历史监测导出", notes = "环境历史监测导出", httpMethod = "POST")
    public void hjInfoExcel(@RequestBody Map<String, Object> condition, HttpServletResponse response) throws IOException {
        if (condition.get("deviceId") == null || Objects.equals(condition.get("deviceId").toString(), "")) {
            return ;
        }
        Device device = deviceService.getById(condition.get("deviceId").toString());
        Massif massif = massifService.getById(device.getMassifId());
        final LambdaQueryWrapper<JcMassifFactorValueLog> lambda = new QueryWrapper<JcMassifFactorValueLog>().lambda();
        if (condition.get("deviceId") != null && !Objects.equals(condition.get("deviceId").toString(), "")) {
            lambda.eq(JcMassifFactorValueLog::getDeviceNo, device.getCode());
        }
        if (condition.get("startDate") != null && !Objects.equals(condition.get("startDate").toString(), "")) {
            lambda.between(JcMassifFactorValueLog::getGmtCreate, DateUtil.getStartTime(DateUtil.parseDate(condition.get("startDate").toString())), DateUtil.getEndTime(DateUtil.parseDate(condition.get("endDate").toString())));
        }
        condition.put("startTime",DateUtil.getStartTime(DateUtil.parseDate(condition.get("startDate").toString())));
        condition.put("endTime",DateUtil.getEndTime(DateUtil.parseDate(condition.get("endDate").toString())));
        condition.put("deviceNo",device.getCode());
        List<String> cnList = new ArrayList<>();
        int idDay = 0;
        if (condition.get("type").toString().equals("1")) {
            cnList.add("2011");
            cnList.add("2021");
        } else if (condition.get("type").toString().equals("2")) {
            cnList.add("2061");
        } else if (condition.get("type").toString().equals("3")) {
            cnList.add("2031");
            cnList.add("2041");
            idDay = 1;
        }
        List<List<String>> headerList = new ArrayList<>();
        headerList.add(Collections.singletonList("项目名称"));
        headerList.add(Collections.singletonList("设备名称"));
        headerList.add(Collections.singletonList("采集时间"));
        List<JcFactor> jcFactorList = jcFactorService.getListByDeviceId(condition.get("deviceId").toString());
        jcFactorList.forEach(e -> {
            headerList.add(Collections.singletonList(e.getName() + "(" + e.getUnitMeasurement() + ")"));
        });

        List<List<String>> bodyList = new ArrayList<>();
        JSONObject jsonObject = new JSONObject();
        if (idDay == 0) {
            lambda.in(JcMassifFactorValueLog::getCn, cnList);
            lambda.eq(JcMassifFactorValueLog::getDelFlag, 0);
            lambda.orderByDesc(JcMassifFactorValueLog::getGmtCreate);
            List<JcMassifFactorValueLog> list1 = this.jcMassifFactorValueLogService.list(lambda);
            List<JcMassifFactorValue> list2 = jcMassifFactorValueService.getList(condition);
            list1.forEach(e -> {
                List<String> list = new ArrayList<>();
                list.add(massif.getName());
                list.add(device.getName());
                list.add(DateUtil.formatTime(e.getGmtCreate()));

                jcFactorList.forEach(k -> {
                    Optional<JcMassifFactorValue> mapOptional = list2.stream().filter(b -> (
                                    b.getJcFactorId().equals(k.getId())&&b.getJcMassifFactorValueLog().equals(e.getId())
                            )
                    ).findFirst();
                    if (mapOptional.isPresent()) {
                        JcMassifFactorValue jcMassifFactorValue = mapOptional.get();
                        list.add(jcMassifFactorValue.getValue()+"");
                    } else {
                        list.add("");
                    }
                });
                bodyList.add(list);
            });


        }else{

            List<Map<String, Object>> mapList=jcMassifFactorValueService.getDayInfo(condition);
            Date startDate = DateUtil.parseDate(condition.get("startDate").toString());
            Date endDate = DateUtil.parseDate(condition.get("endDate").toString());
            while (startDate.compareTo(endDate)<1){
                List<String> list = new ArrayList<>();
                list.add(massif.getName());
                list.add(device.getName());
                list.add(DateUtil.formatTime(startDate));
                Date finalStartDate = startDate;
                jcFactorList.forEach(k -> {
                    Optional<Map<String, Object>> mapOptional = mapList.stream().filter(b -> (
                                    b.get("date").equals(DateUtil.format(finalStartDate))&&b.get("jcFactorId").equals(k.getId())
                            )
                    ).findFirst();
                    if (mapOptional.isPresent()) {
                        Map<String, Object> map1 = mapOptional.get();
                        list.add(map1.get("value")+"");
                    } else {
                        list.add("");
                    }
                });
                bodyList.add(list);
                startDate=DateUtil.addDays(startDate,1);
            }


        }


        jsonObject.put("header", headerList);
        jsonObject.put("body", bodyList);
        Map<String,Object> map = jsonObject;
        response.setHeader("Content-Disposition", "attachment; filename=hjInfoExcel.xlsx");
        // 响应类型,编码
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

        EasyExcel.write(response.getOutputStream()).head((List<List<String>>) map.get("header")).sheet("环境历史监测表").doWrite((List<List<String>>) map.get("body"));
    }


    private static List recursiveReverse(List list) {
        if (list.isEmpty()) {
            return new ArrayList<>();
        } else {
            List reversedList = recursiveReverse(list.subList(1, list.size()));
            reversedList.add(list.get(0));
            return reversedList;
        }
    }

    /**
     * 设备每日峰值
     */
    @ApiOperation(value = "设备每日峰值")
    @PostMapping("/maxDateList")
    public Result maxDateList(@RequestBody Map<String, Object> condition) {
        if (condition.get("massifId") == null || condition.get("massifId").toString().equals("")) {
            return Result.errorResult("项目id为空");
        }
        if (condition.get("date") == null || condition.get("date").toString().equals("")) {
            return Result.errorResult("日期为空");
        }
        condition.put("startTime", condition.get("date").toString() + " 00:00:00");
        condition.put("endTime", condition.get("date").toString() + " 23:59:59");

        final LambdaQueryWrapper<Device> lambda = new QueryWrapper<Device>().lambda();
        //TODO 自己的查询逻辑
        lambda.eq(Device::getMassifId, condition.get("massifId").toString());
        lambda.eq(Device::getType, "13");
        List<Device> list = deviceService.list(lambda);
        Massif massif = massifService.getById(condition.get("massifId").toString());
        List<DeviceMonitorVo> deviceMonitorVoList = new ArrayList<>();
        list.forEach(e -> {
            DeviceMonitorVo deviceMonitorVo = new DeviceMonitorVo();
            deviceMonitorVo.setId(e.getId());
            deviceMonitorVo.setName(e.getName());
            deviceMonitorVo.setMassifName(massif.getName());
            deviceMonitorVo.setType(e.getType());
            deviceMonitorVo.setMassifId(condition.get("massifId").toString());
            condition.put("deviceNo", e.getCode());
            List<Map<String, Object>> maxDateList = jcMassifFactorValueService.getMaxDateList(condition);
            deviceMonitorVo.setMonitorDate(condition.get("date").toString());
            final String[] monitorDataStr = {""};
            List<Map<String, Object>> mapList = new ArrayList<>();
            if (maxDateList != null) {
                List<JcFactor> jcFactorList = jcFactorService.getListByDeviceId(e.getId());
                jcFactorList.forEach(k -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("name", k.getName());
                    map.put("unit", k.getUnitMeasurement());
                    Optional<Map<String, Object>> mapOptional = maxDateList.stream().filter(b -> (
                                    b.get("jcFactorId").toString().equals(k.getId()) && b.get("date").toString().equals(condition.get("date").toString())
                            )
                    ).findFirst();
                    if (mapOptional.isPresent()) {
                        Map<String, Object> mapData = mapOptional.get();
                        map.put("maxDate", mapData.get("maxDate"));
                        map.put("maxValue", mapData.get("maxValue1"));
                    } else {
                        map.put("maxDate", "");
                        map.put("maxValue", "");
                    }
                    mapList.add(map);
                });
                deviceMonitorVo.setMonitorData(mapList);
            }
            deviceMonitorVoList.add(deviceMonitorVo);
        });

        return Result.successResult(deviceMonitorVoList);
    }

    @PostMapping("/maxDateListExcel")
    @ApiOperation(value = "设备每日峰值-导出", notes = "设备每日峰值-导出", httpMethod = "POST")
    public void washCostBedListExcel(@RequestBody Map<String, Object> condition, HttpServletResponse response) {
        if (condition.get("massifId") == null || condition.get("massifId").toString().equals("")) {
            return;
        }
        if (condition.get("date") == null || condition.get("date").toString().equals("")) {
            return;
        }
        condition.put("startTime", condition.get("date").toString() + " 00:00:00");
        condition.put("endTime", condition.get("date").toString() + " 23:59:59");

        final LambdaQueryWrapper<Device> lambda = new QueryWrapper<Device>().lambda();
        //TODO 自己的查询逻辑
        lambda.eq(Device::getMassifId, condition.get("massifId").toString());
        lambda.eq(Device::getType, "13");
        List<Device> list = deviceService.list(lambda);
        Massif massif = massifService.getById(condition.get("massifId").toString());
        List<DeviceMonitorVo> deviceMonitorVoList = new ArrayList<>();
        list.forEach(e -> {
            DeviceMonitorVo deviceMonitorVo = new DeviceMonitorVo();
            deviceMonitorVo.setId(e.getId());
            deviceMonitorVo.setName(e.getName());
            deviceMonitorVo.setMassifName(massif.getName());
            deviceMonitorVo.setType(e.getType());
            deviceMonitorVo.setMassifId(condition.get("massifId").toString());
            condition.put("deviceNo", e.getCode());
            List<Map<String, Object>> maxDateList = jcMassifFactorValueService.getMaxDateList(condition);
            deviceMonitorVo.setMonitorDate(condition.get("date").toString());
            final String[] monitorDataStr = {""};
            if (maxDateList != null) {
                List<JcFactor> jcFactorList = jcFactorService.getListByDeviceId(e.getId());
                jcFactorList.forEach(k -> {
                    monitorDataStr[0] = monitorDataStr[0] + "监测项：" + k.getName() + "  ";
                    Optional<Map<String, Object>> mapOptional = maxDateList.stream().filter(b -> (
                                    b.get("jcFactorId").toString().equals(k.getId()) && b.get("date").toString().equals(condition.get("date").toString())
                            )
                    ).findFirst();
                    if (mapOptional.isPresent()) {
                        Map<String, Object> map = mapOptional.get();
                        monitorDataStr[0] = monitorDataStr[0] + "峰值：" + map.get("maxValue1") + k.getUnitMeasurement() + "  峰值时间:" + map.get("maxDate") + "\n";
                    } else {
                        monitorDataStr[0] = monitorDataStr[0] + "峰值：--  峰值时间:--\n";
                    }
                });
                deviceMonitorVo.setMonitorDataStr(monitorDataStr[0]);
            }
            deviceMonitorVoList.add(deviceMonitorVo);
        });
        EasyExcelUtil.toExcle2(response, deviceMonitorVoList, "设备每日峰值", DeviceMonitorVo.class);


    }


    /**
     * 设备每日峰值
     */
    @ApiOperation(value = "热力图")
    @PostMapping("/heatMap")
    public Result heatMap(@RequestBody Map<String, Object> condition) {
        if (condition.get("massifId") == null || condition.get("massifId").toString().equals("")) {
            return Result.errorResult("项目id为空");
        }
        if (condition.get("type").toString().equals("1")) {
            condition.put("startTime", DateUtil.formatTime(DateUtil.addHour(new Date(), -1)));
            condition.put("endTime", DateUtil.formatTime(new Date()));
        } else if (condition.get("type").toString().equals("2")) {
            condition.put("startTime", DateUtil.formatTime(DateUtil.addDays(new Date(), -1)));
            condition.put("endTime", DateUtil.formatTime(new Date()));
        }

        final LambdaQueryWrapper<Device> lambda = new QueryWrapper<Device>().lambda();
        //TODO 自己的查询逻辑
        lambda.eq(Device::getMassifId, condition.get("massifId").toString());
        lambda.eq(Device::getType, "13");
        List<Device> list = deviceService.list(lambda);
        List<Map<String, Object>> mapList = new ArrayList<>();
        list.forEach(e -> {
            Map<String, Object> map = new HashMap<>();
            map.put("lng", e.getXId());
            map.put("lat", e.getYId());
            int count = 0;
            condition.put("deviceNo", e.getCode());
            List<Map<String, Object>> list2 = jcMassifFactorValueService.getAvgInfo(condition);
            Map<String, Object> mapData = new HashMap<>();
            list2.forEach(k -> {
                mapData.put(k.get("jcFactorId").toString(), k.get("avgValue"));
            });

            if (mapData.get("a34002") != null && mapData.get("a34004") == null) {
                count = calculateAQI_PM10(Double.parseDouble(mapData.get("a34002").toString()));
            } else if (mapData.get("a34002") == null && mapData.get("a34004") != null) {
                count = calculateAQI_PM25(Double.parseDouble(mapData.get("a34004").toString()));
            } else if (mapData.get("a34002") != null && mapData.get("a34004") != null) {
                count = calculateAQI(Double.parseDouble(mapData.get("a34002").toString()), Double.parseDouble(mapData.get("a34004").toString()));
            }
            map.put("count", count);
            mapList.add(map);
        });

        return Result.successResult(mapList);
    }


    // 根据PM10浓度计算对应的AQI值
    public static int calculateAQI_PM10(double pm10) {
        double[] breakpoints = {0, 50, 150, 250, 350, 420, 500};
        double[] aqiValues = {0, 50, 100, 150, 200, 300, 500};
        return calculateAQI(pm10, breakpoints, aqiValues);
    }

    // 根据PM2.5浓度计算对应的AQI值
    public static int calculateAQI_PM25(double pm25) {
        double[] breakpoints = {0, 35, 75, 115, 150, 250, 350};
        double[] aqiValues = {0, 50, 100, 150, 200, 300, 400};
        return calculateAQI(pm25, breakpoints, aqiValues);
    }

    // 根据浓度值和分段点和对应AQI值计算AQI值
    public static int calculateAQI(double concentration, double[] breakpoints, double[] aqiValues) {
        double result = 0;

        for (int i = 0; i < breakpoints.length - 1; i++) {
            if (concentration >= breakpoints[i] && concentration <= breakpoints[i + 1]) {
                result = ((aqiValues[i + 1] - aqiValues[i]) / (breakpoints[i + 1] - breakpoints[i])) * (concentration - breakpoints[i]) + aqiValues[i];
                break;
            }
        }

        return (int) Math.ceil(result);
    }

    // 计算AQI
    public static int calculateAQI(double pm10, double pm25) {
        double aqi = 0;

        // 计算PM10和PM2.5的AQI
        double aqiPM10 = calculateAQI_PM10(pm10);
        double aqiPM25 = calculateAQI_PM25(pm25);

        // 取较大的AQI作为最终结果
        if (aqiPM10 > aqiPM25) {
            aqi = aqiPM10;
        } else {
            aqi = aqiPM25;
        }

        return (int) aqi;
    }

    // 获取健康关注程度
    public static String getHealthConcern(int aqi) {
        if (aqi >= 0 && aqi <= 50) {
            return "优";
        } else if (aqi >= 51 && aqi <= 100) {
            return "良";
        } else if (aqi >= 101 && aqi <= 150) {
            return "轻度污染";
        } else if (aqi >= 151 && aqi <= 200) {
            return "中度污染";
        } else if (aqi >= 201 && aqi <= 300) {
            return "重度污染";
        } else if (aqi >= 301 && aqi <= 500) {
            return "严重污染";
        } else {
            return "AQI值无效";
        }
    }
}
